package middleware

import (
	"gitee.com/lstack_light/go-light/internal/pkg/utils"
	"gitee.com/lstack_light/go-light/internal/web"
	"github.com/logrusorgru/aurora"
	"io/ioutil"
	"net/http"
	"net/http/httputil"
	"strings"
	"time"
)

/**
  @author: light
  @since: 2023/6/3
  @desc: 日志中间件
*/

func Logger(body bool) *web.MiddleWare {
	// 指定中间件的类型,便于控制执行的范围
	key := "logger"
	handler := func(next web.Handler, interceptor map[string][]string) web.Handler {
		return func(w http.ResponseWriter, r *http.Request) {
			flag := false
			for _, group := range interceptor[key] {
				if strings.Contains(r.RequestURI, group) {
					start := time.Now()
					content, err := httputil.DumpRequest(r, body)
					if err != nil {
						utils.GetLogger().Println(aurora.Yellow(err))
						return
					}
					next(w, r)
					resp := "null"
					if nil != r.Response.Body {
						// 读取响应体
						data, readErr := ioutil.ReadAll(r.Response.Body)
						r.Response.Body.Close()
						if nil != readErr {
							utils.GetLogger().Println(aurora.Yellow(err))
							return
						}
						resp = string(data)
					}
					utils.GetLogger().Printf("%s %d %s %s\n%s",
						time.Since(start),
						utils.BeautifyResponseCode(r.Response.StatusCode),
						utils.BeautifyRequestMode(r.Method),
						strings.ReplaceAll(string(content), r.Method, ""),
						"Response:"+resp,
					)
					flag = true
					break
				}
			}
			if !flag {
				next(w, r)
			}
		}
	}
	return &web.MiddleWare{Key: key, CoreHandler: handler}
}
